#include "mqttclient.h"


MqttClient::MqttClient(QWidget *parent, Ui::Widget *ui)
    : QWidget(parent),
      client(new QMqttClient(this)),
      m_ui(ui) // 初始化成员变量
{
    // 可以在这里设置一些初始参数或连接信号槽
        connect(client, &QMqttClient::connected, this, []() {
            qDebug() << "MQTT 客户端连接成功.";
        });
        connect(client, &QMqttClient::disconnected, this, []() {
            qDebug() << "MQTT client disconnected.";
        });
        connect(client, &QMqttClient::messageReceived, this, [](const QByteArray &message, const QMqttTopicName &topic) {
            qDebug() << "Message received:" << message << "from topic:" << topic.name();
        });
}

void MqttClient::connectSever()
{
    qDebug() << "connectSever called.";
    client->setClientId("QTclientId");

    // 设置服务器地址和端口
    client->setHostname("192.168.0.105");
    qDebug() << "Hostname set.";

    client->setPort(1883);
    qDebug() << "Port set.";

    // 连接到服务器
    client->connectToHost();
    qDebug() << "connectToHost called.";

}

void MqttClient::subTopic()
{

    QMqttTopicFilter topic("LoRa_Pub_Topic"); // 替换为你想要订阅的主题
    auto subscription = client->subscribe(topic, 0); // QoS 设置为 0

    if (!subscription) {
        qDebug() << "Failed to subscribe to topic:" << topic;
    } else {
        qDebug() << "Subscribed to topic:" << topic;
        // 订阅成功后可做一些进一步的处理
        connect(subscription, &QMqttSubscription::messageReceived, this, [this](const QMqttMessage &message) {
            qDebug() << "New message received:" << message.payload();

            // 使用成员变量 m_ui
            m_ui->recMessgae->append(message.payload());
        });
    }
}

void MqttClient::pubTopic(const QByteArray &message, const QString &topicName, quint8 qos)
{
    if (client->publish(QMqttTopicName(topicName), message, qos)) {
        qDebug() << "Published message:" << message << "to topic:" << topicName;
    } else {
        qDebug() << "Failed to publish message to topic:" << topicName;
    }
}


